<?php
class Customer_Model_Orders extends Zend_Db_Table_Abstract
{
	protected $_name = 'orders';
	protected $_primary = 'order_id';
	
	/**
	 * Create order
	 * @param int $customerID
	 * @param int $tripID
	 * @param string $code
	 * @return 
	 */
	public function createOrder($customerID, $tripID, $code)
	{
		// get current date
		$dateObj = new Zend_Date();		
		$date = $dateObj->toString('y-MM-dd HH:mm:ss');		
		
		$orderRow = $this->createRow();
		if($orderRow) {
			$orderRow->customer_id = $customerID;
			$orderRow->trip_id = $tripID;
			$orderRow->order_date = $date; 
			$orderRow->code = $code;
			try {				
				$orderID = $orderRow->save();
				return $orderID;
			} catch(Exception $e) {				
				throw new Exception('Could not create order. Unknown exception.');				
			}			
		}
		throw new Exception('Could not create order.');
	}
	
	/**
	 * Delete order
	 * @param int $id
	 * @return int
	 */
	public function deleteOrder($id)
	{
		$orderRow = $this->find($id)->current();
		if($orderRow) {
			try {				
				return $orderRow->delete();
			} catch (Exception $e) {
				throw $e;
			}
		}
		throw new Exception('Could not delete order. Order not found.');
	}
	
	/**
	 * Get order ID by code
	 * @param string $code
	 * @return int|null
	 */
	public function getOrderIDByCode($code)
	{		
		$select = $this->select()->where('code = ?', $code);				
		$r = $this->fetchRow($select);
		return $r ? $r->order_id : null;
	}
	
}